package forum;
import javax.persistence.*;
import java.util.ArrayList;
import javax.ejb.*;
import projet.*;
import agent.*;
import java.util.Date;

/**
 * EJB de gestion des topics
 * @author Geoffroy
 *
 */
@Stateless
@Local
public class TopicEJB implements TopicInterface {

	@PersistenceContext
	EntityManager em;
	@EJB
	ProjetInterface projetManager;
	@EJB
	AgentInterface ownerManager;
	
	public void createTopic(Topic t) {
		em.persist(t);
	}
	
	public Topic findById(int idTopic) {
		return (Topic)em.find(Topic.class,idTopic);
	}

	
	public ArrayList<Topic> findByProjet(int idProjet) {
		return (ArrayList<Topic>)em.createQuery("SELECT t FROM Topic t WHERE t.projet.id="+idProjet).getResultList();
	}
	
	public ArrayList<Post> getPostsFromTopic(int idTopic) {
		return (ArrayList<Post>)em.createQuery("SELECT p FROM Post p WHERE p.topic.id="+idTopic+"ORDER BY p.date").getResultList();
	}
	
	public Projet getProjetFromTopic(int idTopic) {
		Integer id= (Integer)em.createNativeQuery("SELECT projet.id FROM projet INNER JOIN topic ON topic.idProjet = projet.id WHERE topic.id="+idTopic).getSingleResult();
		return (Projet)em.find(Projet.class, id);
	}
	
	@Override
	public void update(Topic t) {
		em.merge(t);
		
	}
	
	
}
